<script lang="ts" setup>
import {onLoad, onPullDownRefresh, onReady} from "@dcloudio/uni-app";
import {computed, getCurrentInstance, onMounted, ref} from "vue";
import {getPicDetailApi} from "@/api/ainmalsList";
import type {PicDetailItem} from "@/types/animals";
import {formatDate_yyyy_mm_dd} from "@/utils/time";
import {addFavApi} from "@/api/detail";
import {useUserStore} from "@/stores/user";
import {IMessage} from "@/components/aw-message/message";
import Comment from "@/subPkg/detail/components/Comment.vue";
import type {GuessAnimalItem} from "@/types/home";
import {getGuessLikeListApi} from "@/api/home";


const userStore = useUserStore()
const {safeAreaInsets, windowWidth} = uni.getSystemInfoSync()
const id = ref()
const cover = ref()
const initHeight = ref(0)
const tags = ref<string[]>([])
onLoad(async (option: any) => {
  id.value = option.id
  cover.value = option.cover
  initHeight.value = option.height || 200
  await getPicDetail()
  if (cover.value !== null) {
    getInitHeight(cover.value)
  }
})
const getInitHeight = (cover: string) => {
  uni.getImageInfo({
    src: cover,
    success: (res) => {
      initHeight.value = windowWidth / res.width * res.height
    },
    fail: (err) => {
      initHeight.value = 200
    }
  })
}
onPullDownRefresh(() => {
  uni.stopPullDownRefresh()
})
const picSetDetail = ref<PicDetailItem>({} as PicDetailItem)
/**
 * 获取图片详细信息
 */
const loading = ref(false)
const getPicDetail = async () => {
  loading.value = true
  const res = await getPicDetailApi(id.value)
  console.log(res.data)
  if (res.data.creator === -1) {
    showInput.value = false
  }
  picSetDetail.value = res.data
  tags.value = picSetDetail.value.tags?.split(',') || []
  loading.value = false
}

let delay = ref(false)
const onClickHeart = async (id: number, like: 0 | 1, type?: 0 | 1) => {
  if (delay.value) {
    return
  }
  delay.value = true
  setTimeout(() => {
    delay.value = false
  }, 200)
  // 判断当前用户是否登录
  if (!userStore.userInfoData?.userID) {
    return uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
  }
  // 判断当前用户是否收藏
  addFavApi(id, like === 0 ? 1 : 0, type).then(res => {
    if (res.code === '1') {
      picSetDetail.value.isLike = picSetDetail.value.isLike === 1 ? 0 : 1
      picSetDetail.value.likes = picSetDetail.value.likes + (like === 0 ? 1 : -1)
      IMessage({
        type: 'success',
        content: like === 0 ? '收藏成功' : '已取消收藏',
        showIcon: true
      })
    }
  })
}


/**
 * 获取评论
 */
const commentPage = ref(1)
const pageSize = 5
const comment = ref()
onReady(async () => {
  comment.value.getComment({page: commentPage.value, pageSize: pageSize, animalId: id.value})
})
const updateComment = () => {
  comment.value.getComment({page: commentPage.value, pageSize: pageSize, animalId: id.value})
}
const showLoadMore = ref(true)
const onNoData = () => {
  showLoadMore.value = false
  showInput.value = true
}

const onLoadMoreComment = () => {
  commentPage.value++
  comment.value.getComment({page: commentPage.value, pageSize: pageSize, animalId: id.value, loadMore: true})
}

const showInput = ref(true)

const goUser = () => {
  const type = userStore.userInfoData?.userID === picSetDetail.value.creator ? 0 : 1
  uni.navigateTo({
    url: '/subPkg/userHomepage/userHomepage?type=' + type +
        '&userId=' + picSetDetail.value.creator
  })
}

const goBack = () => {
  uni.navigateBack({delta: 1})
}

/**
 * 图片加载时触发
 */
const imgOriginHeight = ref(0)
const imgOriginWidth = ref(0)
const imgHeight = computed(() => {
  return (windowWidth / imgOriginWidth.value) * imgOriginHeight.value || 200
})
const onLoadImage = (e: UniHelper.ImageOnLoadEvent) => {
  imgOriginHeight.value = Number(e.detail.height)
  imgOriginWidth.value = Number(e.detail.width)
}

/**
 *  分享
 */
const onShare = () => {
  uni.setClipboardData({
    data: 'http://cuteworld.top/#/subPkg/picDetail/picDetail?id=' + id.value,
    success: function () {
      uni.showToast({
        icon: "none",
        title: '已复制连接ヾ(≧▽≦*)o'
      });
    }
  })
}

/**
 * 查看图片详情
 */
const showImageSwiper = ref(false)
const goPreview = () => {
  showImageSwiper.value = true
  /*  uni.previewImage({
      urls: picSetDetail.value.imageList.map(item=>item.url),
    })*/
}

const hideSwiper = () => {
  showImageSwiper.value = false
  showBtn.value = true
}

const onClickImage = () => {

}
const onClosePreview = () => {
  showImageSwiper.value = false
}

/**
 * 切换图片
 */
const currentIndex = ref(0)
const onChange = (e: UniHelper.SwiperOnChangeEvent) => {
  currentIndex.value = e.detail.current
}

/**
 * 显示底部按钮
 */
const showBtn = ref(true)
const onChangeBtn = () => {
  showBtn.value = !showBtn.value
}

/**
 * 控制动画显示
 */
const showAnimation = ref(true)
onReady(() => {
  setTimeout(() => {
    showAnimation.value = false
  }, 1000)
})

/**
 * 点击下载
 */
const onDownload = async () => {
  // #ifdef H5
  return uni.showToast({
    title: '请长按下载',
    icon: 'none',
    duration: 2500
  })
  // #endif
  await uni.showLoading({
        title: '下载中...',
        mask: true
      }
  )
  setTimeout(() => {
    uni.saveImageToPhotosAlbum({
      filePath: picSetDetail.value.imageList[currentIndex.value].url,
      success: function (result) {
        uni.showToast({
          title: '已保存到相册',
          icon: "success"
        });
      },
      fail: function () {
        uni.showToast({
          icon: 'error',
          title: '下载失败，请检查网络',
        });
      },
      complete: () => {
        uni.hideLoading()
      }
    })
  }, 500)
}


/**
 * 获取猜你喜欢
 */
// 获取猜你喜欢
const guessLikeList = ref<GuessAnimalItem[]>()
const getGuessLikeList = async () => {
  const res = await getGuessLikeListApi(1, 20);
  if (guessLikeList.value) {
    //  加载更多拼接数据
    guessLikeList.value = [...guessLikeList.value, ...res.data.data]
    return
  }
  guessLikeList.value = res.data.data
}
onMounted(() => {
  getGuessLikeList()
})

const scale = ref(1)
const dbClick = () => {
  if (scale.value === 2) {
    scale.value = 1
  } else {
    scale.value = 2
  }
}


const showNav = ref(false)
const instance = getCurrentInstance()
/**
 * 监听滚动
 */
const onScroll = (e: UniHelper.ScrollViewOnScrollEvent) => {
  const hideHeight = initHeight.value + 240
  showNav.value = e.detail.scrollTop > hideHeight;
  if (e.detail.scrollTop > hideHeight)

      // 判断评论区是否超出屏幕顶部
    uni.createSelectorQuery().select('.pic-comment').boundingClientRect((data: any) => {
      showInput.value = data.top + data.height >= 0;
    }).exec()
}

</script>

<template>

  <scroll-view v-show="!showImageSwiper" :scroll-y="true"
               style="width: 100vw;height: 100vh;background: #FFFFFF;position: relative"
               @scroll="onScroll">
    <uni-transition :show="showNav" :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
                    custom-class="creator-nav cuIcon-back"
                    mode-class="slide-top" @tap="goBack">
      <view class="margin-left-sm" @click.stop="goUser">
        <uv-avatar :src="picSetDetail.creatorAvatar" mode="aspectFill" size="30px"></uv-avatar>
      </view>

      <text class="margin-left-sm text-bold text-lg">{{ picSetDetail.creatorName }}</text>
    </uni-transition>

    <view :style="{ top: safeAreaInsets?.top + 'px' }" class="btn cuIcon-back back" @tap="goBack">
    </view>

    <view :style="{ top: safeAreaInsets?.top + 'px' }" class="btn cuIcon-share share" @tap="onShare">
    </view>

    <view>
      <!--    图片  -->
      <view :class="[showAnimation?'scale-up-center-longer':'']" :style="{height:initHeight+'px'}"
            class="  bg-gray" style="width: 100%;position: relative">

        <view v-if="picSetDetail.picNum>1" class="num" @tap="goPreview">
          查看全部 {{ picSetDetail.picNum }}
        </view>
        <uv-image :height="initHeight" :src="cover||picSetDetail?.imageList[0]?.url" mode="widthFix" width="100%"
                  @click="goPreview"
                  @load="onLoadImage">
          <template v-slot:error>
            <view class="flex flex-column justify-center align-center padding-bottom-sm"
                  style="width: 100%;height: 100%;overflow: hidden">
              <uv-image :src="'/static/home-selected.png'" height="100%" mode="aspectFit" width="100%"></uv-image>
              <text class="text-gray text-sm flex justify-center align-center " style="">图片加载失败
              </text>
            </view>
          </template>
        </uv-image>
        <!-- 收藏 -->
        <view :class="[picSetDetail.isLike?'heart-active':'']" class="heart-btn"
              @click.stop="onClickHeart(picSetDetail.id,picSetDetail.isLike,1)">
          <!-- 爱心 -->
          <uv-icon :color="picSetDetail.isLike?'#e3264e':'#abb7c3'" :name="'heart-fill'" size="36"></uv-icon>
          <text :class="['d','heart',picSetDetail.isLike?'active-d':'']"></text>
        </view>
      </view>

      <view class="padding-lg flex flex-column" style="gap: 10px">
        <!--    图片标题  -->
        <view class="title text-bold text-xl text-black">{{ tags[0] }}</view>
        <!--    图片标签  -->
        <view class="tag-list margin-top-sm">
          <view v-for="(item,index) in tags" :key="item">
            <uv-tags :color="'#39c5bb'" :text="'#'+item" bg-color="#EBF9F8" border-color="rgba(255,255,255)"></uv-tags>
          </view>
        </view>
        <!--   点赞数|浏览数   -->
        <view class="margin-top-sm flex justify-start align-center padding-tb-sm"
              style="gap:15px;width: 100%;border-bottom: 1px solid #e3e3e3">
          <view>
            <uni-icons :color="'#e3264e'" type="heart-filled"></uni-icons>
            <text style="margin-left: 3px">{{ picSetDetail.likes }}</text>
          </view>
          <view>
            <uni-icons type="eye"></uni-icons>
            <text style="margin-left: 3px">{{ picSetDetail.viewCount }}</text>
          </view>
          <!--    上传时间  -->
          <view v-show="picSetDetail.createTime" class="text-gray text-sm">
            {{ formatDate_yyyy_mm_dd(new Date(picSetDetail.createTime)) }}
          </view>
        </view>

        <!--      上传者-->
        <view class="flex justify-start align-center padding-tb-sm"
              style="width: 100%;border-bottom: 1px solid #e3e3e3">
          <uv-avatar :src="picSetDetail.creatorAvatar" mode="aspectFill" size="56px" @click="goUser"></uv-avatar>
          <text class="margin-left-sm text-bold text-lg">{{ picSetDetail.creatorName }}</text>
        </view>
      </view>

      <!--    评论区  -->
      <view class="pic-comment" style="padding-bottom: 100rpx;width: 100%;min-height: 200px">
        <Comment ref="comment" :animal-id="id" :show-input="showInput" @noData="onNoData"
                 @update="updateComment"/>
        <view v-if="showLoadMore" class="flex justify-center align-center text-gray margin-top-lg" style="width: 100%"
              @click="onLoadMoreComment">点击加载更多
        </view>
      </view>

    </view>

    <!--    猜你喜欢-->

    <view>
      <aw-animals-list :animals-list="guessLikeList" :hide-text="true" :show-name="false" :top="30">
        <template v-slot:title>
          <view class="guess-like-title flex justify-center align-center margin-bottom-sm">
            <image mode="aspectFit" src="/static/guess-like.png"></image>
            相关推荐
            <image mode="aspectFit" src="/static/guess-like.png"></image>
          </view>
        </template>
      </aw-animals-list>
    </view>
  </scroll-view>

  <view v-if="showImageSwiper" style="position: relative">

    <!--   顶部按钮 -->
    <uni-transition :show="showBtn" :styles="{ top: safeAreaInsets?.top + 'px' }"
                    custom-class="btn cuIcon-close back"
                    mode-class="slide-left" @tap="onClosePreview">
    </uni-transition>
    <uni-transition :show="showBtn" :styles="{ top: safeAreaInsets?.top + 'px' }" custom-class="count"
                    mode-class="slide-right"
                    @tap="goPreview">
      {{ currentIndex + 1 }} / {{ picSetDetail.picNum }}
    </uni-transition>

    <!--  图片切换  -->
    <swiper v-if="picSetDetail.imageList.length>1" class="img-swiper" @change="onChange">
      <swiper-item v-for="(img,index) in picSetDetail.imageList" :key="img.id" class="flex justify-center align-center"
                   style="width: 100%;height: 100%"
                   @click="hideSwiper">

        <view class="image-content">
          <movable-area class="movable-area" scale-area="true">
            <movable-view
                :damping="50"
                :friction="1"
                :inertia="true"
                :scale="true"
                :scale-value="scale"
                animation="true"
                class="movable-view"
                direction="none"
                scale-max="3"
                scale-min="1"
            >
              <view style="width: 100%;transition: all .2s ease-in-out" @dblclick="dbClick" @tap.stop="onClickImage">
                <uv-image :height="index===0?initHeight+'px':''" :src="img.url" mode="widthFix" width="100%"></uv-image>
              </view>
            </movable-view>
          </movable-area>
        </view>
      </swiper-item>
    </swiper>

    <!--   单张图片 -->
    <view v-else class="img-swiper flex justify-center align-center" @click="hideSwiper">
      <view class="image-content">
        <movable-area class="movable-area" scale-area="true">
          <movable-view
              :damping="100"
              :friction=".4"
              :inertia="true"
              :scale="true"
              :scale-value="scale"
              animation="true"
              class="movable-view"
              direction="none"
              scale-max="3"
              scale-min="1"
          >
            <view style="width: 100%;transition: all .2s ease-in-out" @dblclick="dbClick" @tap.stop="onClickImage">
              <uv-image :height="initHeight+'px'" :src="picSetDetail.imageList[0].url" mode="widthFix"
                        width="100%">
                <template v-slot:error>
                  <view class="flex flex-column justify-center align-center padding-bottom-sm"
                        style="width: 100%;height: 100%;overflow: hidden">
                    <uv-image :src="'/static/home-selected.png'" height="100%" mode="aspectFit" width="100%"></uv-image>
                    <text class="text-gray text-sm flex justify-center align-center " style="">图片加载失败
                    </text>
                  </view>
                </template>
              </uv-image>
            </view>
          </movable-view>
        </movable-area>
      </view>
    </view>

    <view :class="['cuIcon-back' ,'showBtn',showBtn?'':'hideBtn']" @click="onChangeBtn"></view>
    <!--  底部按钮  -->
    <uni-transition :show="showBtn" :styles="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
                    custom-class="bottom-btn-box bg-shadeBottom"
                    mode-class="slide-bottom">
      <view class="bottom-btn-box-item cuIcon-share"
            @tap="onShare">
        <text>
          分享
        </text>

      </view>
      <view class="cuIcon-down bottom-btn-box-item " @tap="onDownload">
        <text>
          下载
        </text>

      </view>
      <view :class="[picSetDetail.isLike?'cuIcon-likefill text-red heart-active':'cuIcon-like']"
            class=" bottom-btn-box-item "
            @tap="onClickHeart(picSetDetail.id,picSetDetail.isLike,1)">
        <text>收藏</text>
      </view>
    </uni-transition>
  </view>


</template>

<style lang="scss" scoped>
page {
  background: #FFFFFF;
}

.tag-list {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
  border-radius: 10px;
  gap: 5px;
}

/**
 * 顶部按钮
 */
.btn {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 32px;
  width: 32px;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 50%;
  font-size: 21px;
  color: #FFFFFF;
  position: absolute;
  z-index: 9;
}

.showBtn {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 36px;
  width: 36px;
  border-radius: 50%;
  font-size: 21px;
  color: #FFFFFF;
  position: absolute;
  z-index: 9;
  right: 15px;
  bottom: 65px;
  transform: rotate(-90deg);
  transition: all .2s ease-in-out;
}

.hideBtn {
  transition: all .3s ease-in-out;
  transform: rotate(90deg);
  bottom: 15px;
}

.share {
  right: 20rpx;
  /* #ifdef H5 */
  top: 20rpx !important;
  /* #endif */
}

.num {
  left: 15px;
  bottom: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 3px;
  font-size: 12px;
  color: #FFFFFF;
  position: absolute;
  padding: 5px 8px 5px 8px;
  z-index: 9;
}

.count {
  font-size: 16px;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.4);
  border-radius: 3px;
  color: #FFFFFF;
  position: absolute;
  padding: 5px 8px 5px 8px;
  z-index: 9;
  right: 20rpx;
  /* #ifdef H5 */
  top: 20rpx !important;
  /* #endif */
}

.back {
  left: 20rpx;
  /* #ifdef H5 */
  top: 20rpx !important;
  /* #endif */
}

.img-swiper {
  width: 100vw;
  height: 100vh;
  background: #000;
}

.creator-nav {
  position: fixed;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 3px;
  top: 0;
  width: 100%;
  z-index: 99;
  background: #FFFFFF;
  font-size: 21px;
  padding-left: 10px;
  padding-bottom: 10px;
  /* #ifdef H5 */
  padding-top: 10px !important;
  /* #endif */
}

.bottom-btn-box {
  display: flex;
  align-items: center;
  justify-content: space-around;
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 60px;
  z-index: 99;
  color: #FFFFFF;

  &-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 5px;
    font-size: 24px;

    text {
      font-size: 10px;
    }
  }
}

/* 按钮主体 */
.heart-btn {
  position: absolute; /* 绝对定位 */
  right: 15px;
  bottom: 10px;
  z-index: 1;
}

.heart-active { /* 切换后样式 */
  animation: beat .25s linear forwards;
}

.d {
  --c: #e3264e;
  z-index: 9;
  display: block;
  width: 6px;
  height: 6px;
  background-color: transparent;
  border-radius: 50%;
  /* 绝对定位 居中 */
  position: absolute;
  right: 15px;
  bottom: 10px;
  transform: translate(-50%, -50%) scale(0);
  /* 设置各个方向的阴影 */
  /* 通过var函数调用自定义属性--c,设置阴影颜色 */
  box-shadow: 0 -40px 0 var(--c), 0 40px 0 var(--c), -40px 0 0 var(--c),
  40px 0 0 var(--c), -30px -30px 0 var(--c), 30px -30px 0 var(--c),
  30px 30px 0 var(--c), -30px 30px 0 var(--c);
}

.active-d {
  /* 执行动画: 动画名 时长 加速后减速 停留在最后一帧 */
  animation: blink 0.5s ease-in-out forwards;
  /* 动画延迟时间 */
  animation-delay: 0.3s;
}

/* 心跳动的动画 */
@keyframes beat {
  0% {
    transform: scale(1);
  }
  40% {
    transform: scale(1.2);
  }
  60% {
    transform: scale(1.35);
  }
  80% {
    transform: scale(1.2);
  }
  90% {
    transform: scale(1.15);
  }
  100% {
    transform: scale(1);
  }
}

/* 小圆点闪出的动画 */
@keyframes blink {
  0% {
    transform: translate(-50%, -50%) scale(0.5);
    opacity: 0.8;
  }
  50% {
    transform: translate(-50%, -50%) scale(1);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.1);
    opacity: 0;
  }
}

.guess-like-title {
  font-size: 16px;
  color: #333333;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  image {
    width: 25px;
    height: 25px;
    margin: 0 10px;
  }
}

.image-content {
  width: 100%;

  .movable-area {
    width: 100%;
    //height: 100%;
  }

  .movable-view {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
  }
}
</style>
